<template>
  <div class="login-container">
    <!-- 注册表单 -->
    <el-card
      class="z-1 !border-none w-100 !rounded-4% <sm:w-83 transparent"
      v-if="isRegister"
    >
      <div class="text-center relative">
        <h1>注 册</h1>
      </div>
      <el-form
        ref="loginFormRef"
        autocomplete="off"
        :model="loginData"
        :rules="rules"
      >
        <el-form-item prop="name">
          <span class="res-svg">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            class="flex-1"
            v-model="loginData.name"
            placeholder="姓名"
          />
        </el-form-item>
        <el-form-item prop="username">
          <div class="res-svg">
            <svg-icon icon-class="user" />
          </div>
          <el-input
            v-model="loginData.username"
            class="flex-1"
            placeholder="用户名"
            name="username"
            autocomplete="off"
          />
        </el-form-item>
        <el-tooltip
          :disabled="isCapslock === false"
          content="Caps lock is On"
          placement="right"
        >
          <el-form-item prop="password">
            <span class="res-svg">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              v-model="loginData.password"
              class="flex-1"
              placeholder="密码"
              :type="passwordVisible === false ? 'password' : 'input'"
              name="password"
              @keyup="checkCapslock"
              @keyup.enter="handleLogin"
              autocomplete="off"
            />
            <span class="mr-2" @click="passwordVisible = !passwordVisible">
              <svg-icon
                :icon-class="passwordVisible === false ? 'eye' : 'eye-open'"
                class="cursor-pointer"
              />
            </span>
          </el-form-item>
        </el-tooltip>
        <el-form-item prop="phone">
          <span class="res-svg">
            <svg-icon icon-class="phone" />
          </span>
          <el-input
            class="flex-1"
            v-model="loginData.phone"
            placeholder="电话号码"
            ref="phoneNumber"
          />
        </el-form-item>
        <el-form-item prop="sms_code">
          <span class="res-svg">
            <svg-icon icon-class="captcha" />
          </span>
          <el-input
            placeholder="请输入验证码"
            class="flex-1"
            v-model="loginData.sms_code"
          />
          <span class="span-center">
            <el-button
              type="primary"
              plain
              @click="getCode"
              v-if="isVerify"
              :lodaing="codeLoading"
              >发送验证码</el-button
            >
            <el-button
              type="primary"
              plain
              @click="getCode"
              disabled
              v-else
              :lodaing="codeLoading"
              >{{ timeCount }}秒后重发</el-button
            >
          </span>
        </el-form-item>
        <!-- <el-form-item prop="officeId">
          <span class="res-svg">
            <svg-icon icon-class="college" />
          </span>
          <el-input
            class="flex-1"
            v-model="loginData.officeId"
            placeholder="学院"
          />
        </el-form-item>
        <el-form-item prop="post">
          <span class="res-svg">
            <svg-icon icon-class="position" />
          </span>
          <el-input
            class="flex-1"
            v-model="loginData.post"
            placeholder="职位"
          />
        </el-form-item> -->
        <el-form-item prop="roleId">
          <span class="res-svg">
            <svg-icon icon-class="position" />
          </span>
          <el-radio-group v-model="loginData.roleId">
            <el-radio :value="1">管理员</el-radio>
            <el-radio :value="2">老师</el-radio>
            <el-radio :value="3">学生</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="w-full"
          @click="submitForm"
          >注 册
        </el-button>
        <el-link
          type="primary"
          :underline="false"
          @click="isRegister = false"
          style="margin-top: 16px"
        >
          ← 登录
        </el-link>
      </el-form>
    </el-card>

    <!-- 登录表单 -->
    <el-card
      class="z-1 !border-none w-100 !rounded-4% <sm:w-83 transparent"
      v-else
    >
      <div class="imgtitle items-center justify-center">
        <!-- <img
          src="@/assets/schoolLOGO.png"
          alt="logo"
          class="navbar-logo my-logo"
        /> -->
        <h1 class="ml-2" style="font-weight: normal">讯飞数智化教育平台</h1>
      </div>
      <el-form
        ref="loginFormRef"
        :model="loginData"
        :rules="rules"
        class="login-form"
      >
        <el-form-item prop="username">
          <div class="p-2">
            <svg-icon icon-class="user" />
          </div>
          <el-input
            ref="username"
            v-model="loginData.username"
            class="flex-1"
            size="large"
            placeholder="用户名"
            name="username"
            autocomplete="off"
          />
        </el-form-item>

        <el-tooltip
          :disabled="isCapslock === false"
          content="Caps lock is On"
          placement="right"
        >
          <el-form-item prop="password">
            <span class="p-2">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              v-model="loginData.password"
              class="flex-1"
              placeholder="密码"
              :type="passwordVisible === false ? 'password' : 'input'"
              size="large"
              name="password"
              @keyup="checkCapslock"
              @keyup.enter="handleLogin"
              autocomplete="off"
            />
            <span class="mr-2" @click="passwordVisible = !passwordVisible">
              <svg-icon
                :icon-class="passwordVisible === false ? 'eye' : 'eye-open'"
                class="cursor-pointer"
              />
            </span>
          </el-form-item>
        </el-tooltip>

        <!-- 验证码 -->
        <!-- <el-form-item prop="captchaCode">
          <span class="p-2">
            <svg-icon icon-class="captcha" />
          </span>

          <el-input
            v-model="loginData.captchaCode"
            auto-complete="off"
            placeholder="验证码"
            class="w-[60%]"
            @keyup.enter="handleLogin"
          />

          <div class="captcha">
            <el-image
              :src="captchaBase64"
              @click="getCaptcha"
              :style="{ height: captchaHeight }"
              class="w-[120px] h-[48px] cursor-pointer"
            >
              <template #error>
                <div class="image-slot">
                  <i-ep-picture />
                </div>
              </template>
            </el-image>
          </div>
        </el-form-item> -->

        <el-button
          :loading="loading"
          type="primary"
          class="w-full"
          @click.prevent="handleLogin"
          >登 录
        </el-button>

        <!-- 账号密码提示 -->
        <!-- <div class="mt-10 text-sm">
          <span>用户名: admin</span>
          <span class="ml-4"> 密码: 123456</span>
        </div> -->
        <el-link
          type="primary"
          :underline="false"
          @click="isRegister = true"
          style="margin-top: 16px"
        >
          注册 →
        </el-link>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import router from "@/router";
// import IconEpSunny from "~icons/ep/sunny";
// import IconEpMoon from "~icons/ep/moon";
import { useSettingsStore } from "@/store/modules/settings";

// 状态管理依赖
import { useUserStore } from "@/store/modules/user";
import { useAppStore } from "@/store/modules/app";

// API依赖
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";
import { getCaptchaApi } from "@/api/auth";
import { LoginData } from "@/api/auth/types";
import { register, getPhoneCode } from "@/api/auth/index";
import phone from "@/assets/icons/phone.svg";
import college from "@/assets/icons/college.svg";
import position from "@/assets/icons/position.svg";

// import {
//   User,
//   Lock,
//   Phone,
//   School,
//   OfficeBuilding,
// } from "@element-plus/icons-vue";
// import { fa } from "element-plus/es/locale";

// const settingsStore = useSettingsStore();

// const { title, version } = settingsStore;
// /**
//  * 明亮/暗黑主题切换
//  */
// const isDark = ref<boolean>(settingsStore.theme === "dark");
// const handleThemeChange = (isDark: any) => {
//   useToggle(isDark);
//   settingsStore.changeSetting({
//     key: "theme",
//     value: isDark ? "dark" : "light",
//   });
// };

/**
 * 根据屏幕宽度切换设备模式
 */
const appStore = useAppStore();
const WIDTH = 992; // 响应式布局容器固定宽度  大屏（>=1200px） 中屏（>=992px） 小屏（>=768px）
const { width } = useWindowSize();
watchEffect(() => {
  if (width.value < WIDTH) {
    appStore.toggleDevice("mobile");
  } else {
    appStore.toggleDevice("desktop");
  }
});

const codeLoading = ref(false);
const loading = ref(false); // 按钮loading
const isCapslock = ref(false); // 是否大写锁定
const passwordVisible = ref(false); // 密码是否可见
const captchaBase64 = ref(); // 验证码图片Base64字符串
const loginFormRef = ref(ElForm); // 登录表单ref
const isRegister = ref(false); //决定登录和注册页面

const loginData = ref<LoginData>({
  name: "",
  username: "",
  password: "",
  officeId: "",
  post: "",
  phone: "",
  sms_code: "",
  roleId: "",
});

//注册登录转换时重置表单
watch(isRegister, () => {
  loginFormRef.value.resetFields();
  loginFormRef.value.clearValidate();
});

// const { t } = useI18n();
const rules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: "请输入用户名",
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: "请输入密码",
      },
    ],
    name: [
      {
        required: true,
        trigger: "blur",
        message: "请输入姓名",
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: "blur",
        message: "请输入验证码",
      },
    ],
    phone: [
      {
        required: true,
        trigger: "blur",
        validator: (rule: any, value: any, callback: any) => {
          if (value.length !== 11) {
            callback(new Error("请输入正确的手机号码"));
          } else {
            callback();
          }
        },
        message: "请输入电话号码",
      },
    ],
    officeId: [
      {
        required: true,
        trigger: "blur",
        message: "请输入学院",
      },
    ],
    post: [
      {
        required: true,
        trigger: "blur",
        message: "请输入职位",
      },
    ],
    sms_code: [
      {
        required: true,
        trigger: "blur",
        message: "请输入验证码",
      },
    ],
    roleId: [
      {
        required: true,
        trigger: "blur",
        message: "请选择角色",
      },
    ],
  };
});

/**
 * 检查输入大小写状态
 */
function checkCapslock(e: any) {
  const { key } = e;
  isCapslock.value = key && key.length === 1 && key >= "A" && key <= "Z";
}

/**
 * 获取图形验证码
 */
// function getCaptcha() {
//   getCaptchaApi().then(({ data }) => {
//     loginData.value.captchaKey = data.captchaKey;
//     captchaBase64.value = data.captchaBase64;
//   });
// }
// /**
//  * 根据组件大小调整验证码图片高度
//  */
// const captchaHeight = computed(() => {
//   if (appStore.size === "large") {
//     return "56px";
//   } else if (appStore.size === "small") {
//     return "40px";
//   }
//   return "48px";
// });

/**
 * 登录
 */
const route = useRoute();
const userStore = useUserStore();
function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginData.value)
        .then(() => {
          const query: LocationQuery = route.query;

          const redirect = (query.redirect as LocationQueryValue) ?? "/";

          const otherQueryParams = Object.keys(query).reduce(
            (acc: any, cur: string) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            },
            {}
          );

          router.push({ path: redirect, query: otherQueryParams });
        })
        // .catch(() => {
        //   // 验证失败，重新生成验证码
        //   // getCaptcha();
        // })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}
onMounted(() => {
  // getCaptcha();

  // 主题初始化
  const theme = useSettingsStore().theme;
  useSettingsStore().changeSetting({ key: "theme", value: theme });
  if (theme == "dark") {
    document.documentElement.classList.add("dark");
  } else {
    document.documentElement.classList.remove("dark");
  }
});

/**
 * 注册页面
 */
//验证码获取
let timeCount = ref(60);
const isVerify = ref(true);
let timer: NodeJS.Timeout | null = null; // 用于保存定时器ID
function getCode(): void {
  console.log(loginData.value.phone);
  if (!loginData.value.phone) {
    ElMessage.error("手机号不能为空");
    return;
  }
  if (!/^1[3456789]\d{9}$/.test(loginData.value.phone)) {
    ElMessage.error("请输入正确的手机号码");
    return;
  }

  if (timer !== null) {
    clearInterval(timer); // 清除旧的定时器
  }
  isVerify.value = false;
  timer = setInterval(() => {
    if (timeCount.value > 1) {
      timeCount.value--;
      console.log(timeCount.value);
    } else {
      timeCount.value = 60;
      isVerify.value = true;
      if (timer !== null) {
        clearInterval(timer); // 当计数结束时清除定时器
      }
      timer = null; // 重置定时器ID
    }
  }, 1000);
  getPhoneCode(loginData.value).then(() => {
    ElMessage.success("请查看手机信息获取验证码");
  });
}

/**
 * 注册
 */
const submitForm = async () => {
  await loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      await register(loginData.value).then(() => {
        ElMessage.success("注册成功");
        isRegister.value = false;
      });
    } else {
      ElMessage.error("注册失败");
    }
  });

  isRegister.value = false;
};
</script>

<style lang="scss" scoped>
.login-container {
  @apply w-full h-full flex-center;
  /* 溢出隐藏 */
  height: 100vh;
  overflow-x: hidden;
  display: flex;
  /* 渐变方向从左到右 */
  background: linear-gradient(to right, rgb(247, 209, 215), rgb(191, 227, 241));
  background-repeat: no-repeat;
  background-position: center right;
  background-size: cover;
  image-rendering: pixelated;

  .login-form {
    padding: 30px 10px;

    .captcha {
      position: absolute;
      top: 0;
      right: 0;

      .image-slot {
        display: flex;
        align-items: center;
        justify-content: right;
        width: 100%;
        height: 100%;
        font-size: 18px;
        color: var(--el-text-color-secondary);
        background: var(--el-fill-color-light);

        svg {
          margin-right: 10px;
        }
      }
    }
  }

  .imgtitle {
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    margin-top: 20px;
    color: rgb(0, 0, 0);
    /* 禁止选中 */
    user-select: none;
    letter-spacing: 5px;
    text-shadow: 4px 4px 3px rgba(169, 142, 142, 0.4);
  }

  .transparent {
    background-color: rgb(255 255 255 / 95%);
  }

  .my-logo {
    width: 40px; /* 你可以根据需要调整这个值 */
    height: 40px; /* 你可以根据需要调整这个值 */
  }

  .ml-2 {
    margin-left: 20px; /* 设置标题和图片之间的间距为20px */
  }

  .span-center {
    margin-right: 1px;
    margin-bottom: 1px;
  }
}

.el-form-item {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      transition: background-color 1000s ease-in-out 0s; /* 通过延时渲染背景色变相去除背景颜色 */
    }
  }
}
.text-center {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  margin-top: 20px;
  color: rgb(0, 0, 0);
  /* 禁止选中 */
  user-select: none;
  letter-spacing: 5px;
  text-shadow: 4px 4px 3px rgba(169, 142, 142, 0.4);
}

.res-svg {
  padding: 0 8px;
}
</style>
